package cn.innosmart.aq.view.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.HashMap;

import cn.innosmart.aq.R;
import cn.innosmart.aq.adapter.RuleDeviceAdapter;
import cn.innosmart.aq.bean.AquariumBean;
import cn.innosmart.aq.bean.DeviceBean;
import cn.innosmart.aq.bean.RuleBean;
import cn.innosmart.aq.bean.TriggerBean;
import cn.innosmart.aq.customize.CustomsizeDialog;
import cn.innosmart.aq.util.DeviceConstant;
import cn.innosmart.aq.util.SystemConstant;
import cn.innosmart.aq.view.activity.RuleActivity;


/**
 * Created by Woody on 2015/4/3.
 */
public class RuleStep1Fragment extends BaseFragment {
    private final int CONDITIONCONFIRM = 1;
    private View view;
    private ListView lv_trigger;
    private RuleDeviceAdapter ruleDeviceAdapter;
    private AquariumBean aquariumBean;
    private ArrayList<String> triggers;
    private RuleBean ruleBean;
    private HashMap<String, TriggerBean> triggerBeanHashMap;
    private android.os.Handler mHandler = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case CONDITIONCONFIRM:
                    ruleDeviceAdapter.update(triggerBeanHashMap);
                    break;
            }
        }
    };
    private View.OnClickListener onModifyClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.rl_edit_value:
                    //编辑值
                    TriggerBean triggerBean = (TriggerBean) v.getTag();
                    showModfyValueDialog(triggerBean);
                    break;
                case R.id.rl_checkbox:
                    //勾选框勾选
                    CheckBox cb = (CheckBox) v.getTag();
                    if (cb.isChecked())
                        cb.setChecked(false);
                    else
                        cb.setChecked(true);
                    break;
            }

        }
    };
    private CompoundButton.OnCheckedChangeListener onCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
            DeviceBean deviceBean = (DeviceBean) buttonView.getTag();
            if (isChecked) {
                showSetValueDialog(buttonView, isChecked, deviceBean);
            } else {
                triggerBeanHashMap.remove(deviceBean.getAddress());
                ruleDeviceAdapter.notifyDataSetChanged();
            }
        }
    };

    public static RuleStep1Fragment newInstance(AquariumBean aquariumBean) {
        RuleStep1Fragment f = new RuleStep1Fragment();
        Bundle args = new Bundle();
        args.putParcelable("aquarium", aquariumBean);
        f.setArguments(args);
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_rule_step1, container, false);
        aquariumBean = SystemConstant.currentAquariumBean;
        //列出所有的触发类设备
        triggers = new ArrayList<String>();
        triggers.addAll((ArrayList<String>) aquariumBean.getPhs().clone());
        triggers.addAll((ArrayList<String>) aquariumBean.getTemperatures().clone());
        triggers.addAll((ArrayList<String>) aquariumBean.getWaterLevers().clone());
//        triggers.addAll((ArrayList<String>) aquariumBean.getSwitchDevices().clone());

        ruleBean = RuleActivity.ruleBean;
        triggerBeanHashMap = ruleBean.getTriggers();
        if (triggerBeanHashMap == null) {
            triggerBeanHashMap = new HashMap<String, TriggerBean>();
            ruleBean.setTriggers(triggerBeanHashMap);
        }
        ruleDeviceAdapter = new RuleDeviceAdapter(getActivity(), triggers, triggerBeanHashMap);
        ruleDeviceAdapter.setCheckedChangerListener(onCheckedChangeListener);
        ruleDeviceAdapter.setOnModifyClickListener(onModifyClickListener);
        lv_trigger = (ListView) view.findViewById(R.id.lv_trigger);
        lv_trigger.setAdapter(ruleDeviceAdapter);
        return view;
    }

    /**
     * 设置修改值得对话框
     *
     * @param triggerBean
     */
    private void showModfyValueDialog(final TriggerBean triggerBean) {
        final CustomsizeDialog modifyValueDialog = new CustomsizeDialog(getActivity());
        modifyValueDialog.setTitle(getActivity().getString(R.string.fragment_rule_add_trigger_dialog_title));
        modifyValueDialog.setCanceledOnTouchOutside(false);
        modifyValueDialog.showTriggerValue(triggerBean);
        modifyValueDialog.setPositiveButton(getActivity().getString(R.string.sure), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String result = modifyValueDialog.checkInput(SystemConstant.deviceBeanHashMap.get(triggerBean.getAddress()));
                if (result == null) {
                    showToast(getString(R.string.input_need_number));
                    return;
                } else if (result.equals("True")) {
                } else {
                    showToast(result);
                    return;
                }
                modifyValueDialog.changeTriggerValue(triggerBean);
                mHandler.sendEmptyMessage(CONDITIONCONFIRM);
                //隐藏Dialog
                modifyValueDialog.dismiss();
            }
        });
        modifyValueDialog.setNegativeButton(getActivity().getString(R.string.cancel), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                modifyValueDialog.dismiss();
            }
        });
        modifyValueDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                if (SystemConstant.deviceBeanHashMap.get(triggerBean.getAddress()).getFunctype() == DeviceConstant.FUNCTYPE_TEMPERATURE ||
                        SystemConstant.deviceBeanHashMap.get(triggerBean.getAddress()).getFunctype() == DeviceConstant.FUNCTYPE_PH) {
                    showInputMethod();
                }
// showInputMethod();
//                ((EditText) modifyValueDialog.findViewById(R.id.et_trigger_value)).requestFocus();
            }
        });
        modifyValueDialog.show();
    }

    private void showInputMethod() {
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
    }

    /**
     * 设置值的对话框
     *
     * @param buttonView
     * @param isChecked
     * @param deviceBean
     */
    private void showSetValueDialog(final CompoundButton buttonView, final boolean isChecked, final DeviceBean deviceBean) {
        final CustomsizeDialog setValueDialog = new CustomsizeDialog(getActivity());
        setValueDialog.setTitle(getActivity().getString(R.string.fragment_rule_add_trigger_dialog_title));
        setValueDialog.setCanceledOnTouchOutside(false);
        setValueDialog.setTriggerCondition(deviceBean);
        ((EditText) setValueDialog.findViewById(R.id.et_trigger_value)).requestFocus();
        setValueDialog.setPositiveButton(getActivity().getString(R.string.sure), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String result = setValueDialog.checkInput(deviceBean);
                if (result == null) {
                    showToast(getString(R.string.input_need_number));
                    return;
                } else if (result.equals("True")) {
                } else {
                    showToast(result);
                    return;
                }
                TriggerBean triggerBean = setValueDialog.getTriggerBean(deviceBean);
                triggerBeanHashMap.put(triggerBean.getAddress(), triggerBean);
                mHandler.sendEmptyMessage(CONDITIONCONFIRM);
                //隐藏Dialog
                setValueDialog.dismiss();
            }
        });
        setValueDialog.setNegativeButton(getActivity().getString(R.string.cancel), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                buttonView.setChecked(!isChecked);
                setValueDialog.dismiss();
            }
        });
        setValueDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                showInputMethod();
            }
        });
        setValueDialog.show();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

}
